package com.luoran.kaka.action;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.luoran.kaka.entity.CompanyInfo;
import com.luoran.kaka.entity.PicInfo;
import com.luoran.kaka.service.IAboutInfoService;
import com.luoran.kaka.service.ICompanyInfoService;
import com.luoran.kaka.service.IExtraInfoService;
import com.luoran.kaka.service.IPicInfoService;
import com.luoran.kaka.utils.UUID;

@Controller
@RequestMapping("/company")
public class CompanyInfoAction {

	private static final Logger log = LoggerFactory.getLogger(CompanyInfoAction.class);

	@Autowired
	private Environment evn;
	@Autowired
	private IPicInfoService picInfoService;
	@Autowired
	private ICompanyInfoService companyInfoService;
	@Autowired
	IExtraInfoService extraInfoService;
	@Autowired
	IAboutInfoService aboutInfoService;

	@RequestMapping("/info")
	public String infoPage() {
		return "company/company-info";
	}

	@RequestMapping("/create/{openId}")
	public String addpage(@PathVariable("openId") String openId, Model model) {
		log.info("跳转到新建公司名片页面,参数openId为{{}}", openId);
		model.addAttribute("openId", openId);
		return "company/company-create";
	}

	/**
	 * 根据id删除企业
	 */
	@RequestMapping("/delete/{id}")
	@ResponseBody
	public JSONObject deleteCompany(@PathVariable("id") String id) {
		JSONObject obj = new JSONObject();
		int result = companyInfoService.deleteById(id);
		if (result == 1) {
			obj.put("result", result);
			obj.put("flag", true);
		} else {
			obj.put("flag", false);
		}
		return obj;
	}

	/**
	 * 
	 * update: 修改企业信息
	 */
	@RequestMapping("/update")
	@ResponseBody
	public JSONObject update(CompanyInfo companyInfo) {
		JSONObject obj = new JSONObject();
		int result = companyInfoService.updateById(companyInfo);
		if (result == 1) {
			obj.put("flag", true);
		} else {
			obj.put("flag", false);
		}
		return obj;
	}

	/**
	 * findById: 根据id查询对象
	 */
//	@RequestMapping("/view/{id}")
//	public String findById(@PathVariable("id") String id, Model model) {
//		log.info("查看企业名片详情,当前参数id为:{{}}",id);
//		CompanyInfo company = companyInfoService.getCompanyInfoById(id);
//		//List<AboutInfo> aboutList=aboutInfoService.getAboutInfosById(id);
//		if(aboutList.size()>0) {
//			Map<String, String> describeMap=new HashMap<>();
//			Map<String, List<PicInfo>> imgMap=new HashMap<>();
//			AboutInfo aboutInfo=null;
//			PicInfo picInfo=null;
//			List<PicInfo> picList=null;
//			for (int i = 0; i < aboutList.size(); i++) {
//				aboutInfo = aboutList.get(i);
//				describeMap.put(aboutInfo.getId(), aboutInfo.getTextContext());
//				String[] ids=aboutInfo.getPicIds().split(",");
//				picList=new ArrayList<>();
//				for (int j = 0; j < ids.length; j++) {
//					picInfo=picInfoService.getPicInfoById(ids[j]);
//					picList.add(picInfo);
//				}
//				imgMap.put(aboutInfo.getId(), picList);
//			}
//			model.addAttribute("describeMap", describeMap);
//			model.addAttribute("imgMap", imgMap);
//		}
//		
//		String extraInfoId = company.getExtraInfoId();
//		if (!StringUtils.isEmpty(extraInfoId)) {
//			ExtraInfo extra = extraInfoService.getExtraInfoById(extraInfoId);
//			JSONObject extraInfo = JSONObject.parseObject(extra.getExtraInfo());
//			model.addAttribute("extra", extraInfo);
//		}
//		model.addAttribute("company", company);
//		return "company/company-info";
//	}

	/**
	 * addCompany:新增公司信息
	 */
	@RequestMapping("/insert")
	@ResponseBody
	public JSONObject addCompany(CompanyInfo companyInfo) {
		JSONObject obj = new JSONObject();
		String companyId = companyInfoService.addCompany(companyInfo);
		if (!StringUtils.isEmpty(companyId)) {
			obj.put("companyId", companyId);
			obj.put("msg", "保存成功!");
			obj.put("flag", true);
		} else {
			obj.put("msg", "保存失败!");
			obj.put("msg", false);
		}
		return obj;
	}

	/**
	 * upload:上传图片
	 */
	@RequestMapping("/upload")
	@ResponseBody
	public JSONObject upload(HttpServletRequest req) {
		JSONObject obj = new JSONObject();
		PicInfo pic = new PicInfo();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
		Iterator<String> fileNames = multipartRequest.getFileNames();
		MultipartFile file = multipartRequest.getFile(fileNames.next());
		String originalName = file.getOriginalFilename();// 源文件名称
		String suffix = originalName.substring(originalName.lastIndexOf(".")).toLowerCase();// 原始后缀小写
		long size = file.getSize();// 源文件大小
		String path = evn.getProperty("file.path");// 获取图片存储目录
		String newFileName = UUID.get() + suffix;// 根据UUID生成新的文件名称带后缀
		String depositUrl = path + "/" + newFileName;
		File dest = new File(depositUrl);// 上传目标路径
		try {
			if (!dest.getParentFile().exists()) {
				dest.getParentFile().mkdirs();
				log.info("父及目录不存在，创建父及目录。");
			}
			file.transferTo(dest);// 图片上传
			pic.setOriginalName(originalName);
			pic.setSize((int) size);
			pic.setName(newFileName);
			pic.setDepositUrl(depositUrl);
			pic.setUrl(evn.getProperty("file.path.url") + req.getContextPath() + "/" + newFileName);// 根据配置的虚拟路径可以直接用url访问本地图片,正式上线可以通过nginx反向代理访问linux图片目录
			pic.setCreatetime(new Date());
			pic.setLastupdatetime(new Date());
			String picId = picInfoService.insertPic(pic);
			if (null != picId) {
				log.info("图片上传成功");
				obj.put("picId", picId);
			}
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return obj;
	}
}
